package com.zxbit.flash.network;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.zxbit.flash.BuildConfig;
import com.zxbit.flash.PopApplication;
import com.zxbit.flash.utils.LogUtils;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by zhanglibo on 2018/1/20.
 */

public class RetrofitHelper {
    private static RetrofitHelper helper;
    private static Retrofit mRetrofit;

    public static RetrofitHelper getRetorfitHelper() {
        if (helper == null) {
            helper = new RetrofitHelper();
            helper.initHelper();
        }


        return helper;
    }

    public void initHelper() {
        // 创建 OKHttpClient
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (Urls.BASE_URL.startsWith("https")) {
            try {
                setCertificates(builder, PopApplication.getContext().getAssets().open("https.pem"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        builder.connectTimeout(15, TimeUnit.SECONDS);//连接超时时间
        builder.writeTimeout(20, TimeUnit.SECONDS);//写操作 超时时间
        builder.readTimeout(20, TimeUnit.SECONDS);//读操作超时时间
        builder.retryOnConnectionFailure(true);

        //todo log日志 正式上线请取消
        if(BuildConfig.DEBUG){
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor
                    .Logger() {
                @Override
                public void log(String message) {
                    if (message.trim().startsWith("{\"")) {
                        LogUtils.json(message);
                    }else {
                        LogUtils.iWithTag("netLog",message);
                    }
                }
            });
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logging);
        }

        // 创建Retrofit
        mRetrofit = new Retrofit.Builder()
                .client(builder.build())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Urls.BASE_URL)
                .build();

    }

    public ApiService getApiService() {
        return mRetrofit.create(ApiService.class);
    }

    public Retrofit getRetrofitClient() {
        return mRetrofit;
    }


    /**
     * 通过okhttpClient来设置证书
     *
     * @param clientBuilder OKhttpClient.builder
     * @param certificates  读取证书的InputStream
     */
    public void setCertificates(OkHttpClient.Builder clientBuilder, InputStream... certificates) {
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            int index = 0;
            for (InputStream certificate : certificates) {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificateFactory
                        .generateCertificate(certificate));
                try {
                    if (certificate != null)
                        certificate.close();
                } catch (IOException e) {
                }
            }
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                    TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:"
                        + Arrays.toString(trustManagers));
            }
            X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            clientBuilder.sslSocketFactory(sslSocketFactory, trustManager);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
